/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim </a>, 2004
 */
package hk.com.carfield.core;

import hk.com.carfield.util.LogUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.IOUtils;

/**
 * @author carfield
 */
public final class Context {
	public static Context getTestContext() {
		try {
			return new Context();
		} catch (final Exception e) {
			throw new RuntimeException(e);
		}
	}

	public final CacheManager cacheMan = new CacheManager();

	public volatile Config config;

	public final MailManager mailMan;

	public final PersistenceManager persistMan;

	final ScheduleManager scheduleManager = new ScheduleManager();

	public final TemplateManager templateMan = new TemplateManager();

	private Context() throws IOException {
		config = Config.getTestConfig();
		mailMan = new MailManager(0, "", "");
		persistMan = new PersistenceManager(config);
		commonInit();
	}

	public Context(final File dataRoot, final String dbName) throws IOException {
		try {
			IOUtils.copy(
					new URL("http://checkip.dyndns.org:8245/").openStream(),
					System.out);
		} catch (final Exception e) {
			e.printStackTrace();
		}
		config = Config.getConfig(new File(dataRoot, "conf"));
		mailMan = new MailManager(25, config.getSmtpHost(),
				config.getAdminEmail());
		persistMan = new PersistenceManager(config);
		commonInit();
	}

	private void commonInit() throws IOException {
		LogUtil.init(config.dataRoot);
		scheduleManager.involve(Context.this);
	}

	public void executeTasks(final Request r, final File l) throws IOException {
		scheduleManager.involve(this, r, l);
	}

	public void shutdown() {
		cacheMan.shutdown();
	}
}